﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Tilemaps;
using static UnityEngine.Networking.UnityWebRequest;

namespace Hydrogen.MarkovChain.SolidMap2DScene
{
    public class SolidMap2dResManager : ResourceManager
    {
        protected Dictionary<SolidType, SolidTile> _resCache = new Dictionary<SolidType, SolidTile>();

        public SolidTile GetTile(SolidType solidType)
        {
            if (this._resCache.TryGetValue(solidType, out SolidTile tile))
                return tile;

            var addr = SolidMap2dResConstant.GetTileAddr(solidType);
            try
            {
                var result = Load<SolidTile>(addr);
                if (result)
                    this._resCache[solidType] = result;
                return result;
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                return null;
            }
        }

        public override void Dispose()
        {
            foreach (var tile in _resCache.Values)
            {
                if (!tile) continue;
                Addressables.Release(tile);
            }
        }

        /// <summary>
        /// 获取规则的 xml 文本
        /// </summary>
        public string GetRuleText(string ruleXmlAddr)
        {
            string result = "";
            try
            {
                var textAsset = Load<TextAsset>(ruleXmlAddr);
                if (textAsset)
                {
                    result = textAsset.text;
                    Addressables.Release(textAsset);
                }
                return result;
            }
            catch (Exception ex)
            {
                Debug.Log(ex);
                return result;
            }
        }
    }
}
